package com.malljelly.study.controller;

import com.alibaba.fastjson.JSONObject;
import com.malljelly.study.service.PayCallBackService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by 骑着蜗牛去旅行 on 2018/8/30.
 */
@Api("支付宝接口文档")
@RestController  //@Controller+@ResponseBody
@RequestMapping("soa/aliPayService")
@Slf4j
public class CallBackController {

    @Autowired
    private PayCallBackService payCallBackService;
    // 错误页面
    private static final String ERROR = "";
    private static final String PAY_SUCCESS = "pay_success";


    /**
     * 同步回调地址  AlipayConfig中已配置
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("/callBack/synCallBack")
    public void synCallBack(HttpServletRequest request, HttpServletResponse response) throws IOException {

        response.setContentType("text/html;charset=utf-8");
        Map<String, String[]> requestParams = request.getParameterMap();
        Map<String, String> params = new HashMap<String, String>();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        PrintWriter writer = response.getWriter();

        //同步回调
        JSONObject result = payCallBackService.synCallBack(params);
        Object code = result.get("code");
        if(-1==  Integer.parseInt(code.toString()) ){
            //调到错误页面
            return ;
        }
        //商户订单号
        String out_trade_no = (String)result.get("out_trade_no");
        //支付宝交易号
        String trade_no = (String)result.get("trade_no");
       // 付款金额
        String total_amount = (String)result.get("total_amount");
        String htmlFrom = "<form name='punchout_form'"
                + " method='post' action='http://127.0.0.1/soa/aliPayService/callBack/synSuccessPage' >"
                + "<input type='hidden' name='outTradeNo' value='" + out_trade_no + "'>"
                + "<input type='hidden' name='tradeNo' value='" + trade_no + "'>"
                + "<input type='hidden' name='totalAmount' value='" + total_amount + "'>"
                + "<input type='submit' value='立即支付' style='display:none'>"
                + "</form><script>document.forms[0].submit();" + "</script>";
        writer.println(htmlFrom);
        writer.close();
    }

    // 同步回调,解决隐藏参数
    @RequestMapping(value = "/callBack/synSuccessPage", method = RequestMethod.POST)
    public String synSuccessPage(HttpServletRequest request, String outTradeNo, String tradeNo, String totalAmount) {
        request.setAttribute("outTradeNo", outTradeNo);
        request.setAttribute("tradeNo", tradeNo);
        request.setAttribute("totalAmount", totalAmount);
        return PAY_SUCCESS;
    }


    /**
     * 异步回调地址  AlipayConfig中已配置
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("/callBack/asynCallBack")
    public String asynCallBack(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String, String[]> requestParams = request.getParameterMap();
        Map<String, String> params = new HashMap<String, String>();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        return payCallBackService.asynCallBack(params);
    }

}
